package mygang.controller;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import mygang.helper.ControllerHelper;
import mygang.helper.JsonHelper;
import mygang.model.CustomResponse;
import mygang.model.Role;
import mygang.model.User;
import mygang.service.manager.RoleService;
import mygang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 */
@Controller
public class AuthenticationController extends AbstractController {
    
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    
    @RequestMapping("/login")
    public ModelAndView login() {
        return new ModelAndView("login");
    }
    
    @RequestMapping("/logout")
    public String logout() {
        return "redirect:j_spring_security_logout";
    }
    
    @RequestMapping("/registration")
    public ModelAndView registration() {
        return new ModelAndView("registration");
    }
    
    @RequestMapping(value = "/registration/isUserUnique", method = RequestMethod.POST)
    
    public @ResponseBody Boolean isUserUnique(@RequestParam(required = true, value = "login") String login) throws IOException {
        return userService.findByLogin(login).getLogin()==null;
    }
    
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public void register(@RequestParam(required = true, value = "login") String login, 
                        @RequestParam(required = true, value = "password") String password, 
                        @RequestParam(required = false, value = "roles") String roles,
                        HttpServletResponse response) throws IOException {
        
        //cannot add user with existed login
        if(!isUserUnique(login)){ 
            CustomResponse result = new CustomResponse(
                CustomResponse.Result.FAILURE, 
                "login", 
                "Current login already exists.", 
                "Error!");
            
            JsonHelper.prepareJsonResponse(result, response);
            return;
        }
        
        // collects roles
        Set<Role> rolesSet = new HashSet<Role>();
        if (roles != null && !roles.trim().equals("")) {
            
            List<Role> allRoles = roleService.getAll();
            for (String role : roles.split(",")) {
                Role userRole = new Role();
                try {
                    Long id = Long.valueOf(role);
                    userRole.setId(id);
                    rolesSet.add(allRoles.get(allRoles.indexOf(userRole)));
                } catch (NumberFormatException ex) {
                    //skip
                }
            }
        }
        
        try {
            userService.add(new User(login, password));
            
            CustomResponse result = new CustomResponse(
                CustomResponse.Result.SUCCESS, 
                "login", 
                "You have been successfully registered.", 
                "Success!");
        
            JsonHelper.prepareJsonResponse(result, response);
        } catch (Exception ex) {
            ControllerHelper.handleException(ex, response);
        }
    }
}
